package com.example.pingze.service;

import com.example.pingze.entity.Compete;
import com.example.pingze.entity.Ranking;
import com.example.pingze.repository.RankingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;


@Service
public class RankingService {
    @Autowired
    private RankingRepository repository;
    public List<Ranking> findRankingsByKeyword(String keyword) {
        return repository.findRankingsByKeywordOrderByCountDesc(keyword);
    }

    // 在ranking表中新增一条数据
    public Ranking addRanking(Compete compete) {
        String keyWord = compete.getKeyWord();
        String account = compete.getAccount();
        String nickName = compete.getNickName();
        Ranking ranking = new Ranking();
        ranking.setId(UUID.randomUUID().toString());
        ranking.setAccount(account);
        ranking.setNickName(nickName);
        ranking.setCount(1);
        ranking.setKeyword(keyWord);
        return repository.save(ranking);
    }

    public Ranking findRankingByAccountAndKeyword(String account, String keyword) {
        return repository.findRankingByAccountAndKeyword(account, keyword);
    }

    public Ranking subRanking(Ranking ranking) {
        if (ranking.getCount() > 0){
            int num = ranking.getCount() - 1;
            ranking.setCount(num);
            return repository.save(ranking);
        }else {
            return null;
        }
    }

    public Ranking plusRanking(Ranking ranking) {
        int num = ranking.getCount() + 1;
        ranking.setCount(num);
        return repository.save(ranking);
    }
}
